package net.qhzw.admin.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.qhzw.admin.config.JwtTokenUtil;
import net.qhzw.admin.config.JwtUserDetailsService;
import net.qhzw.admin.entity.SysUser;
import net.qhzw.admin.mapper.SysUserMapper;
import net.qhzw.admin.model.*;
import net.qhzw.admin.param.SysUserLoginParam;
import net.qhzw.admin.param.SysUserParam;
import net.qhzw.admin.pojo.SysUserVo;
import net.qhzw.admin.query.SysUserQuery;
import net.qhzw.admin.service.SysUserService;
import net.qhzw.common.model.JsonResult;
import net.qhzw.common.util.StringUtils;
import net.qhzw.common.util.UUIDUtil;
import org.apache.catalina.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private JwtUserDetailsService userDetailsService;

    @Value("${jwt.header}")
    private String tokenHeader;


    /***
     * 登录以后返回token
     * @param param 用户名 密码
     * @return 调用认证中心返回结果
     */
    @Override
    public JsonResult loginAuthentication(JwtRequest param) {
        try {
            authenticate(param.getUsername(), param.getPassword());
            final UserDetails userDetails = userDetailsService
                    .loadUserByUsername(param.getUsername());
            final String token = jwtTokenUtil.generateToken(userDetails);
            return JsonResult.success(new JwtResponse(token));
        }catch (Exception e){
            return JsonResult.error(e.getMessage());
        }
    }
//    @Override
//    public JsonResult login(SysUserLoginParam param) {
//        Map<String, String> resultMap = new HashMap<>();
//        SysUser user = userMapper.selectByUsername(param.getUsername());
//        if (user == null) {
//            return JsonResult.error("输入的用户不存在");
//        }
//        if (!BCrypt.checkpw(param.getPassword(), user.getPassword())) {
//            return JsonResult.error("密码错误");
//        }
//        resultMap.put("token", user.getId());
//        return JsonResult.success(resultMap);
//    }


    /***
     * 获取用户信息
     * @param request
     * @return
     */
    @Override
    public JsonResult userInfo(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader).substring(7);
        String username = jwtTokenUtil.getUsernameFromToken(token);
        SecurityUser userInfo =(SecurityUser) userDetailsService.loadUserByUsername(username);
        return JsonResult.success(userInfo);
    }


    /****
     * 添加后台管理用户
     * @param param
     * @return
     */
    @Override
    public JsonResult editSysUser(SysUserParam param) {
        if (param.getId() != null && !param.getId().isEmpty()) {
            SysUser user = new SysUser();
            BeanUtils.copyProperties(param, user);
            user.setPassword(BCrypt.hashpw(param.getPassword(), BCrypt.gensalt()));
            int row = userMapper.updateByPrimaryKeySelective(user);
            return result(row, "error");
        }
        if (param.getUsername() == null || StringUtils.isEmpty(param.getUsername())) {
            return JsonResult.error("用户名不能为空");
        }
        if (param.getPassword() == null || StringUtils.isEmpty(param.getPassword())) {
            return JsonResult.error("密码不能为空");
        }

        int count = userMapper.selectCountByUsername(param.getUsername());
        if (count > 0) {
            return JsonResult.error("用户名已存在，请更换用户名");
        }
        SysUser user = new SysUser();
        BeanUtils.copyProperties(param, user);
        user.setId(UUIDUtil.getUUid());
        user.setCreateTime(new Date());
        user.setStatus(1);
        user.setPassword(BCrypt.hashpw(param.getPassword(), BCrypt.gensalt()));
        int row = userMapper.insertSelective(user);
        return result(row, "error");
    }


    /***
     * 删除后台管理用户
     * @param id
     * @return
     */
    @Override
    public JsonResult deleteSysUser(String id) {
        int row = userMapper.deleteByPrimaryKey(id);
        return result(row, "error");
    }


    @Override
    public JsonResult getSysUser(String id) {
        SysUserVo user = userMapper.selectUserVoKey(id);
        return JsonResult.success(user);
    }

    @Override
    public JsonResult getSysUserList(SysUserQuery query) {
        Map<String, Object> result = new HashMap<>();
        PageHelper.startPage(query.getPage(), query.getLimit());
        List<SysUserVo> userList = userMapper.selectList(query);
        PageInfo<SysUserVo> pageInfo = new PageInfo<>(userList);
        result.put("total", pageInfo.getTotal());
        result.put("list", pageInfo.getList());
        return JsonResult.success(result);
    }


    /***
     * 个人信息修改
     * @param param
     * @return
     */
    @Override
    public JsonResult updateUserInfo(SysUserParam param) {
        SysUser user = userMapper.selectByPrimaryKey(param.getId());
        if (!BCrypt.checkpw(param.getOldPassword(), user.getPassword())) {
            return JsonResult.error("原密码密码错误");
        }
        user.setPassword(BCrypt.hashpw(param.getPassword(), BCrypt.gensalt()));
        int row = userMapper.updateByPrimaryKeySelective(user);
        return result(row, null);
    }



    /***
     * 判断修改数据库返回值 返回
     * @param row
     * @param msg
     * @return
     */
    private JsonResult result(int row, String msg) {
        if (row > 0) {
            return JsonResult.success();
        }
        return JsonResult.error(null, msg);
    }

    private void authenticate(String username, String password) throws Exception {
        try {
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (DisabledException e) {
            throw new Exception("USER_DISABLED", e);
        } catch (BadCredentialsException e) {
            throw new Exception("密码错误", e);
        }
    }

}
